#include "myhead.h"

int main()
{
    int tcpsock = socket(AF_INET, SOCK_STREAM, 0);
    if(tcpsock == -1)
    {
        perror("socket");
        return -1;
    }

    int opt = 1;
    setsockopt(tcpsock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in myaddr = 
    {
        .sin_family = AF_INET,
        .sin_port = htons(5000),
        .sin_addr.s_addr = INADDR_ANY
    };

    if(bind(tcpsock, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1)
    {
        perror("bind");
        close(tcpsock);
        return -1;
    }

    if(listen(tcpsock, 10) == -1)
    {
        perror("listen");
        close(tcpsock);
        return -1;
    }

    printf("服务器启动，监听端口5000...\n");

    while(1)
    {
        struct sockaddr_in save_addr;
        socklen_t size = sizeof(save_addr);
        int newsock = accept(tcpsock, (struct sockaddr *)&save_addr, &size);
        if(newsock == -1)
        {
            perror("accept");
            continue;
        }

        printf("新的客户端连接\n");

        char path[50] = "";
        int ret = recv(newsock, path, sizeof(path) - 1, 0);
        if(ret == -1)
        {
            perror("recv");
            close(newsock);
            continue;
        }
        else if(ret == 0)
        {
            printf("客户端断开连接\n");
            close(newsock);
            continue;
        }
        
        path[ret] = '\0'; // 确保字符串结束
        printf("请求文件: %s\n", path);

        if(access(path, F_OK) == -1)
        {
            printf("文件不存在: %s\n", path);
            if(send(newsock, "nohave", 6, 0) == -1)
            {
                perror("send");
            }
            close(newsock);
            continue;
        }

        printf("文件存在，开始传输\n");
        if(send(newsock, "have", 4, 0) == -1)
        {
            perror("send");
            close(newsock);
            continue;
        }

        int fd = open(path, O_RDONLY);
        if(fd == -1)
        {
            perror("open");
            close(newsock);
            continue;
        }

        char copy[512] = "";
        ssize_t read_bytes;
        
        while((read_bytes = read(fd, copy, sizeof(copy))) > 0)
        {
            ret = send(newsock, copy, read_bytes, 0);
            if(ret == -1)
            {
                perror("send");
                break;
            }
            else if(ret == 0)
            {
                printf("客户端断开连接\n");
                break;
            }
            usleep(1000); // 稍微延迟，避免发送过快
        }

        close(fd);

        // 发送结束标记
        if(send(newsock, "all_ok", 6, 0) == -1)
        {
            perror("发送结束标记失败");
        }
        else
        {
            printf("文件传输完成: %s\n", path);
        }

        close(newsock);
    }

    close(tcpsock);
    return 0;
    printf("验证\n");
}